//
//  LPFOAuthVC.swift
//  WeiBo
//
//  Created by mac on 16/4/17.
//  Copyright © 2016年 mac. All rights reserved.
//

/*
https://api.weibo.com/oauth2/authorize

App Key：573366319
App Secret：607d66d59667cb7726c9947594e99ca6


document.getElementById('userId').value='test';document.getElementById('passwd').value='123456'

https://www.baidu.com/?code=7e37a34e8c9d7d809cde6fdea0ec77fa
*/

import UIKit

import SVProgressHUD

class LPFOAuthVC: UIViewController {
    
    override func loadView() {
        view = webView
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
        let request = NSURLRequest(URL: url!)
        
//        print(url)
        
        webView.loadRequest(request)
        
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
    }
    
    // MARK: - 设置视图
    @objc private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }
    // MARK: - 设置导航栏
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancle")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
        navigationItem.title = "微博登陆"
    }
    
    // MARK: - 监听事件
    @objc private func cancle(){

        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func auto(){
        //自动充入 js注入
        let jsString = "document.getElementById('userId').value='\(LPFweiboName)';document.getElementById('passwd').value='\(LPFweiboPasswd)'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    // MARK: - webView
    private lazy var webView:UIWebView = UIWebView()

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
extension LPFOAuthVC:UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
//        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
//        SVProgressHUD.dismiss()
        
    }
    
    /*
    请求的urlOptional("https://api.weibo.com/oauth2/authorize")
    请求的urlOptional("https://api.weibo.com/oauth2/authorize#")
    请求的urlOptional("https://api.weibo.com/oauth2/authorize")
    请求的urlOptional("http://www.baidu.com/?code=91e0c2af1b20de72c4d3d62a29451bf0")
    请求的urlOptional("https://m.baidu.com/?code=91e0c2af1b20de72c4d3d62a29451bf0&from=844b&vit=fps")
    */
    
    // webView将要加载url的时候 会调用该方法 如果我们是使用代理方法 默认返回true
    // 如果我们叫他返回false 将不再加载该请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
         // 判断我们的urlString是否有值 二进制前缀是否是我们回调页
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(REDIRECT_URI) {
            // 判断我们的request 的请求参数是否存在
            if let q = request.URL?.query{
                //字符串截取code
                let code = q.substringFromIndex("code=".endIndex)
                print("code的值\(code)")
                getUserAccount(code)
                return false
            }
        }
        
        return true
    }
}

extension LPFOAuthVC{
    // MARK: - 请求accessToken
    func getUserAccount(code: String){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = [
            "client_id":APPKEY,
            "client_secret":APPSECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":REDIRECT_URI
        ]
        
        LPFNetworkTools.sharedTools.request(LPFRequestMethod.POST, urlString: urlString, params: params) { (response, error) -> () in
            if error != nil{
                print(error)
                return
            }
            
            guard let dataDic = response as? [String: AnyObject] else{
                print("返回值不是字典")
                return
            }
            
            let account = LPFUserAccountModel(dict: dataDic)
            //获取用户数据
            self.getUserInfo(account)
        }
    }
    
    // MARK: - 获取用户数据
    func getUserInfo(account: LPFUserAccountModel){
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let pararms = [
            "access_token":account.access_token!,
            "uid":account.uid!
        ]
        
        LPFNetworkTools.sharedTools.request(LPFRequestMethod.GET, urlString: urlString, params: pararms) { (response, error) -> () in
            if error != nil{
                print(error)
                return
            }
            
            guard let dataDic = response as? [String: AnyObject] else{
                print("返回值不是字典")
                return
            }
            // 对我们的account 的头像和昵称赋值
            account.avatar_large = dataDic["avatar_large"] as? String
            account.screen_name = dataDic["screen_name"] as? String
            
            // 对用户数据进行保存
            LPFUserAccountTools.sharedTools.saveUserAccount(account)
            
            //去除当前控制器
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                // 发送通知告知appdelegate帮我们切换根视图
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchDefaultVcNSNotification, object: nil)
            })
        }
    }
}
